package com.siyoumi.sh.modules.yuexiu;

import com.siyoumi.sh.modules.common.HandleBase;
import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.yuexiu.entity.YueXiuApiToken;
import com.siyoumi.sh.modules.yuexiu.entity.YueXiuSignData;
import com.siyoumi.util.*;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//越秀集团
@Slf4j
public class YueXiuHandle
        extends HandleBase
        implements IHandle {
    @Override
    public void run() {
        List<YueXiuApiToken> tokenArr = getArrToken();
        if (tokenArr.size() <= 0) {
            log.error("未配置YUEXIU_TOKEN");
            return;
        }
        XLog.info(this.getClass(), "BEGIN:" + XDate.toDateTimeString());


        StringBuilder sendMsg = new StringBuilder();
        logAndSet(sendMsg, "**越秀签到** \n\n");

        for (YueXiuApiToken item : tokenArr) {
            logAndSet(sendMsg, XStr.concat("**", item.getPhone(), "** \n\n"));
            signInArr(item, sendMsg);

            XReturn r = getFun(item);
            if (r.ok()) {
                Map mapFun = r.getData("data");
                logAndSet(sendMsg, XStr.concat(item.getPhone(), "-积分：" + mapFun.get("points"), "\n\n"));
            } else {
                logAndSet(sendMsg, XStr.concat(item.getPhone(), "-积分：", r.getErrMsg(), "\n\n"));
            }
        }
        //发信息
        sendMsg(sendMsg.toString());

        XLog.info(this.getClass(), "END:" + XDate.toDateTimeString());
    }

    /**
     * token格式
     * token|phone|openid|cid|tokenCheck@token2|phone2|openid2|cid2|tokenCheck2
     * <p>
     * cid格式
     * 100098213#33a13fc608bc4ea9a0ee175703bbe41b,100098213#33a13fc608bc4ea9a0ee175703bbe41b
     */
    protected List<YueXiuApiToken> getArrToken() {
        String token = System.getenv("YUEXIU_TOKEN");
        if (XStr.isNullOrEmpty(token)) {
            return new ArrayList<>();
        }

        List<YueXiuApiToken> tokenArr = new ArrayList<>();
        String[] jmTokenArr = token.split("@");
        for (String s : jmTokenArr) {
            String[] dataArr = s.split("\\|");
            if (dataArr.length > 3) {
                tokenArr.add(YueXiuApiToken.getIns(dataArr[0], dataArr[1], dataArr[2], dataArr[3], dataArr[4]));
            } else {
                tokenArr.add(YueXiuApiToken.getIns(dataArr[0], dataArr[1], dataArr[2], dataArr[3]));
            }
        }

        return tokenArr;
    }

    //签到
    private void signInArr(YueXiuApiToken data, StringBuilder sendMsg) {
        List<YueXiuSignData> signDataArr = data.getSignData();

        for (YueXiuSignData signData : signDataArr) {
            XReturn r = signIn(data, signData);
            logAndSet(sendMsg, XStr.concat(data.getPhone(), "-签到", signData.getCid(), "：", r.getErrMsg(), "\n\n"));
            XApp.sleep(1);
            logAndSet(sendMsg, XStr.concat(data.getPhone(), "停1秒 \n\n"));
        }
    }

    //签到
    private XReturn signIn(YueXiuApiToken tokenData, YueXiuSignData signData) {
        String url = "https://appsmall-yuelife.yuexiuproperty.cn/wxapp-sign/signRecord";

        Map<String, Object> postData = new HashMap<>();
        postData.put("cardNo", signData.getCid());
        postData.put("channelId", 1037);
        postData.put("marketId", signData.getMarketId());
        postData.put("mobile", tokenData.getPhone());
        postData.put("openid", tokenData.getOpenid());

        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.postJson(url, apiHeader(tokenData.getToken()), postData);
        return paresR(returnStr);
    }

    //获取积分
    private XReturn getFun(YueXiuApiToken data) {
        if (XStr.isNullOrEmpty(data.getTokenCheckFun())) {
            return XReturn.getR(20089, "未配置查询token");
        }

        String url = "https://member-gateway.yuexiu.com/gateway/pointsAccount/app/queryAccount";

        Map<String, Object> postData = new HashMap<>();
        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.postJson(url, apiHeader(data.getTokenCheckFun()), postData);
        log.debug(returnStr);

        XReturn r = XReturn.parse(returnStr);

        r.setErrCode(123456);
        Boolean success = r.getData("success", false);
        String message = r.getData("msg");
        if (success) {
            r.setErrCode(0);
        }
        r.setErrMsg(message);

        return r;
    }


    private XReturn paresR(String returnStr) {
        XReturn r = XReturn.parse(returnStr);
        String message = r.getData("msg");
        Integer code = r.getData("code");
        if (code == 200) {
            //200，视为成功
            code = 0;
        }

        r.setErrMsg(message);
        r.setErrCode(code);

        return r;
    }


    private Map<String, String> apiHeader(String token) {
        Map<String, String> headers = new HashMap<>();
        headers.put("xweb_xhr", "1");
        headers.put("token", token);

        return headers;
    }
}
